package com.example.journalegocentrique;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import com.markupartist.android.widget.ActionBar;
import android.media.ThumbnailUtils;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.content.res.Configuration;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.PixelFormat;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.Toast;

@SuppressLint("SimpleDateFormat")
public class ManagePhoto extends Activity {

	private static Intent takePictureIntent = new Intent(
			MediaStore.ACTION_IMAGE_CAPTURE);
	private static final String JPEG_FILE_PREFIX = "IMG_";
	private static final String JPEG_FILE_SUFFIX = ".jpg";
	private static String mCurrentPhotoPath;
	static Uri contentUri;
	private AlbumStorageDirFactory mAlbumStorageDirFactory = null;
	private static File pathFile;
	File tmpphotoFile = null;
	public MyOpenHelper oh;
	public static boolean landMode = false;
	public static boolean newPhoto = false;
	public static boolean photoTacked = false;
	public static Context ctx=null;

	public static boolean isIntentAvailable(Context context, String action) {
		final PackageManager packageManager = context.getPackageManager();
		final Intent intent = new Intent(action);
		List<ResolveInfo> list = packageManager.queryIntentActivities(intent,
				PackageManager.MATCH_DEFAULT_ONLY);
		return list.size() > 0;
	}
	
	// Starting take picture intent
	private void dispatchTakePictureIntent(int actionCode) {
		File f = null;
			try {
				f = setUpPhotoFile();
				mCurrentPhotoPath = f.getAbsolutePath();
				takePictureIntent
						.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
			} catch (IOException e) {
				e.printStackTrace();
				f = null;
				mCurrentPhotoPath = null;
			}
			newPhoto = true;
			startActivityForResult(takePictureIntent, actionCode);
	}
	
	// Getting Album Name
	private String getAlbumName() {
		return getString(R.string.album_name);
	}
	
	// Getting Album Directory
	private File getAlbumDir() {
		File storageDir = null;

		if (Environment.MEDIA_MOUNTED.equals(Environment
				.getExternalStorageState())) {

			storageDir = mAlbumStorageDirFactory
					.getAlbumStorageDir(getAlbumName());

			if (storageDir != null) {
				if (!storageDir.mkdirs()) {
					if (!storageDir.exists()) {
						Log.d("CameraSample", "failed to create directory");
						return null;
					}
				}
			}

		} else {
			Log.v(getString(R.string.app_name),
					"External storage is not mounted READ/WRITE.");
		}

		return storageDir;
	}
	
	// Creating image file
	private File createImageFile() throws IOException {
		// Create an image file name
		String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
				.format(new Date());
		String imageFileName = JPEG_FILE_PREFIX + timeStamp + "_";
		File albumF = getAlbumDir();
		File imageF = File.createTempFile(imageFileName, JPEG_FILE_SUFFIX,
				albumF);
		return imageF;
	}

	private File setUpPhotoFile() throws IOException {

		File f = createImageFile();
		mCurrentPhotoPath = f.getAbsolutePath();

		return f;
	}

	private static void handleBigCameraPhoto() {

		if (mCurrentPhotoPath != null) {
			galleryAddPic();
			mCurrentPhotoPath = null;
		}

	}
	
	// Confirm photo file with path in the gallery
	private static void galleryAddPic() {
		Intent mediaScanIntent = new Intent(
				"android.intent.action.MEDIA_SCANNER_SCAN_FILE");
		File f = new File(mCurrentPhotoPath);
		contentUri = Uri.fromFile(f);
		mediaScanIntent.setData(contentUri);
		ctx.sendBroadcast(mediaScanIntent);
		pathFile = f;
	}


	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		setContentView(R.layout.manage_photo);
		ctx=this;
		// ActionBar
		final ActionBar actionBar = (ActionBar) findViewById(R.id.actionbar);
		actionBar.setTitle("Home");
			
		oh = new MyOpenHelper(this);
		getWindow().setFormat(PixelFormat.RGBA_8888); // Avoid display errors
		
		// Getting Album Directory in storage
		mAlbumStorageDirFactory = new BaseAlbumDirFactory();

			
		// Image view with the photo
		ImageView startPhoto = (ImageView) findViewById(R.id.photoAct4);
		startPhoto.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				dispatchTakePictureIntent(0);
				photoTacked = true;

			}
		});
		
		// Cancel button
		ImageButton cancel = (ImageButton) findViewById(R.id.dispatchPhoto);
		cancel.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				newPhoto = false;
				finish();

			}
		});
		cancel.getBackground().setAlpha(222);

		ImageButton confirmPhoto = (ImageButton) findViewById(R.id.confirmPhoto);
		confirmPhoto.getBackground().setAlpha(222);
		
		//When picture is confirmed
		confirmPhoto.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				// /mnt/sdcard/Pictures/Galleria    (path)
				handleBigCameraPhoto();
				String pkg = getPackageName();

				// Saving photo's path in the database
				Context ctx = EntryDetails.getContext();
				// Checking if the photo is for a new day
				if (newPhoto == true)
					if (ctx != null) { // Checking context
						SQLiteDatabase data1;
						MyOpenHelper mo = new MyOpenHelper(ctx);
						ContentValues values = new ContentValues();
						data1 = mo.getWritableDatabase();
						
						String now = UtilityDB.getCurrentDate();
						data1 = mo.getWritableDatabase();
						if (UtilityDB.getIdDayFromDate(now) == -1) {
	
							values.put(
									MyOpenHelper.DAY,
									UtilityDB.getCurrentDate());
							values.put(MyOpenHelper.PHOTO, pathFile.toString());
							values.put(
									MyOpenHelper.HOUR,
									UtilityDB.getCurrentHour());
							data1.insert(MyOpenHelper.TABLEday, null, values);
							values.clear();
							data1.close();
						} else { // Change the current photo of the day
							SQLiteDatabase database = GetDataBase.getDb();
							values.put("photo", pathFile.toString());
							int idDay = UtilityDB.getIdDayFromDate(now);
							database.update("tbDay", values, "_id =" + idDay, null);
							database.close();
							data1.close();
						}
						newPhoto = false;
					}	
				else {
					SQLiteDatabase database = GetDataBase.getDb();
					ContentValues values = new ContentValues();
					String now = UtilityDB.getCurrentDate();
					values.put("photo", pathFile.toString());
					int idDay = UtilityDB.getIdDayFromDate(now);
					database.update("tbDay", values, "_id =" + idDay, null);
					database.close();
				}
				
				// Starting EntryDetails intent passing photo's path
				Intent intent = new Intent();
				intent.putExtra(pkg + ".path", pathFile);
				setResult(RESULT_OK, intent);
				finish();
			}
		});
		
		// Checking if the camera's intent must be started
		if (landMode == false && photoTacked == false && newPhoto == false){
			dispatchTakePictureIntent(0); // Starts intent
		}
		else {
			try {
				handleSmallCameraPhotoNoIntent(); // Puts picture in the imageView
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		photoTacked =false;
	}

	public boolean onCreateOptionsMenu(Menu menu) {
		MenuItem mi = menu.add(0, 1, 0, "Preferenze");
		mi.setIcon(android.R.drawable.ic_menu_manage);
		return true;
	}

	public boolean onOptionsItemSelected(MenuItem item) {
		if (item.getItemId() == 1) {
			Intent intent = new Intent(this, Preferences.class);
			startActivity(intent);
			return true;
		}
		return super.onOptionsItemSelected(item);
	}
			
	// Setting photo in activity's imageView
	private void handleSmallCameraPhotoNoIntent() throws FileNotFoundException,
			IOException {
		ImageView photoAct4 = (ImageView) findViewById(R.id.photoAct4);
		if (mCurrentPhotoPath != null)
				photoAct4.setImageBitmap(OrientationPicture
				.changeOrientation(mCurrentPhotoPath));
		if(photoTacked==true)
			newPhoto=true;
		else
			newPhoto=false;

	}

	// Managing data received from system's camera
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
			try {
				int result=resultCode; // Checking resultCode for different types of device
				if ((data!=null && result != 0) || result==-1){
					newPhoto = true;
					photoTacked = true;
					handleSmallCameraPhotoNoIntent();// Puts picture in the imageView
				}	
				else { // Picks up the photo from the database if it exists 
					newPhoto = true;
					SQLiteDatabase database = null;
					try {
						database = GetDataBase.getDb();
					} catch (Exception e) {
						Toast.makeText(ManagePhoto.this,
								"Errore nella lettura del database", Toast.LENGTH_SHORT)
								.show();
					}
					String now = UtilityDB.getCurrentDate();
					int idNow = UtilityDB.getIdDayFromDate(now);
					ImageView imagephoto = (ImageView) findViewById(R.id.photoAct4);
					String queryphoto = "SELECT * FROM tbDay WHERE _id=" + idNow;
					String pathphoto = null;
					Cursor cursorPhoto = database.rawQuery(queryphoto, null);
					mCurrentPhotoPath = null;
					if (cursorPhoto.getCount() > 0) {
						cursorPhoto.moveToNext();
						pathphoto = cursorPhoto.getString(2);
						mCurrentPhotoPath = pathphoto;
						
						if (pathphoto != null) {
							pathFile = new File(pathphoto);
							Bitmap bmp1 = null;
							try {
								bmp1 = OrientationPicture.changeOrientation(pathphoto);
								Bitmap b1 = ThumbnailUtils.extractThumbnail(bmp1, 210, 300);
								imagephoto.setImageBitmap(b1);
							} catch (IOException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
							// Setting photo in activity's imageView
							ImageView photoAct4=(ImageView) findViewById(R.id.photoAct4);
							photoAct4.setImageBitmap(OrientationPicture.changeOrientation(pathphoto));
						}
					
					
				}
					cursorPhoto.close();
			database.close();
			}
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	}
	
	// Initializing support variables
	@Override
	protected void onPause(){ 
		super.onPause();
		photoTacked = false;
		newPhoto = false;
	}

	// Checking configuration's change
	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		// TODO Auto-generated method stub
		super.onConfigurationChanged(newConfig);

		if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {

			landMode = true;

		} else {

			landMode = false;

		}
	}

}
